package top.healthylife.gateway.platform.softwind.api.api.authorizationcallback;

/**
 * @author : GaoZeXi
 * @date 2021/7/21 14:19
 */

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.healthylife.gateway.core.service.ParentFace;
import top.healthylife.gateway.dto.annotation.ApiServiceExplain;
import top.healthylife.gateway.platform.softwind.api.config.SystemConfig;
import top.healthylife.gateway.platform.softwind.api.util.AESUtils;
import top.healthylife.gateway.platform.softwind.api.util.WindHttpUtil;
import top.healthylife.gateway.platform.softwind.dto.authorizationcallback.req.WindReqAuthorizationCallBackDto;
import top.healthylife.gateway.platform.softwind.dto.authorizationcallback.res.WindResAuthorizationCallBackDto;

import java.util.Map;

/**
 * @author : GaoZeXi
 * @date 2021/7/14 17:47
 */
@Slf4j
@Service
@ApiServiceExplain( docUrl="https://wfq2020.com/channel-admin/#/login", price = 20, apiName = "授权回调", info = "授权回调")
public class WindAuthorizationCallbackApi implements ParentFace<WindReqAuthorizationCallBackDto, WindResAuthorizationCallBackDto> {

    static final String URL = "https://www.wfq2020.com/auth/#/authorization";


    @Override
    public WindResAuthorizationCallBackDto execute(WindReqAuthorizationCallBackDto windReqAuthorizationCallBackDto) {
        log.info("接收到授权请求");
        //1.回调地址
        String cbUrl = windReqAuthorizationCallBackDto.getCbUrl();
        SystemConfig systemConfig = WindHttpUtil.systemConfigInfo();
        //2.渠道身份(授权)
        String webAuthorizeChannelCode = systemConfig.getWebAuthorizeChannelCode();
        log.info("当前环境渠道身份授权码:{}", webAuthorizeChannelCode);
        //3.设置回调地址
        Map<String, Object> map = BeanUtil.beanToMap(windReqAuthorizationCallBackDto);
        map.remove("cbUrl");
        String json = JSONObject.toJSONString(map);
        JSONObject jsonObject = JSONObject.parseObject(json);
        //加密参数
        String encrypt = AESUtils.encodeBase64(jsonObject);
        log.info("参数加密后:{}", encrypt);
//        String decrypt = AESUtils.decryptBase64(encrypt);
//        log.info("参数解密后:{}", decrypt);
        String finalUrl = StrUtil.format("{}?webAuthorizeChannelCode={}&cburl={}&message={}"
                , URL, webAuthorizeChannelCode, cbUrl, encrypt);
        WindResAuthorizationCallBackDto windResAuthorizationCallBackDto = new WindResAuthorizationCallBackDto()
                .setH5Link(finalUrl);
        log.info("授权请求的url:{}", finalUrl);
        return windResAuthorizationCallBackDto;
    }

}
